/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

/**
 * 分页彩虹算法<br>
 * 通过传入的信息，生成一个分页列表显示
 * [4,5,6,7,8]
 * @param currentPage 当前页
 * @param pageCount 总页数
 * @param displayCount 每屏展示的页数
 * @return 分页条
 */
const rainbow = (currentPage, pageCount, displayCount = 5) => {
  currentPage = Number(currentPage)
  let isEven = true
  isEven = displayCount % 2 == 0
  const left = displayCount / 2
  let right = displayCount / 2

  let length = displayCount
  if (isEven) {
    right++
  }
  if (pageCount < displayCount) {
    length = pageCount
  }
  const result = new Array(length)
  if (pageCount >= displayCount) {
    if (currentPage <= left) {
      for (let i = 0; i < result.length; i++) {
        result[i] = i + 1
      }
    } else if (currentPage > pageCount - right) {
      for (let i = 0; i < result.length; i++) {
        result[i] = i + pageCount - displayCount + 1
      }
    } else {
      for (let i = 0; i < result.length; i++) {
        result[i] = i + currentPage - left + (isEven ? 1 : 0)
      }
    }
  } else {
    for (let i = 0; i < result.length; i++) {
      result[i] = i + 1
    }
  }
  const ceilResult = []
  result.forEach(resultItem => {
    ceilResult.push(Math.ceil(resultItem))
  })
  return ceilResult
}

/**
 * 基于分页彩虹算法之上生成分页带 '...' 的分页算法<br>
 * 通过传入的信息，生成一个分页列表显示
 *
 * [1, '...',4,5,6,7,8, '...', 10]
 * @param currentPage 当前页
 * @param pageCount 总页数
 * @param displayCount 每屏展示的页数
 * @return 分页条
 */
const rainbowWithDot = (currentPage, pageCount, displayCount = 5) => {
  const rainbowResult = rainbow(currentPage, pageCount, displayCount)
  const rainbowResultLength = rainbowResult.length
  // 如果页数足够小，直接返回展示的页数
  if (rainbowResultLength < displayCount) {
    return rainbowResult
  }

  let result = []
  if (rainbowResult[0] === 2) {
    result.push(1)
  }
  if (rainbowResult[0] > 2) {
    result.push(1)
    result.push('...')
  }
  result = result.concat(rainbowResult)
  if (rainbowResult[rainbowResultLength - 1] === pageCount - 1) {
    result.push(pageCount)
  }

  if (rainbowResult[rainbowResultLength - 1] < pageCount - 1) {
    result.push('...')
    result.push(pageCount)
  }
  return result
}

export {
  rainbow,
  rainbowWithDot
}
